﻿using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Dotnet.Utils.Utility.Xml
{
    public class XMLExtensions
    {
        private class Utf8StringWriter : StringWriter
        {
            public override Encoding Encoding => Encoding.UTF8;
        }

        /// <summary>
        /// 对象序列化为XML字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">Model实体对象</param>
        /// <returns></returns>
        public static string Serialize<T>(T t)
        {
            XmlWriterSettings settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };
            XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
            using (StringWriter stringWriter = new Utf8StringWriter())
            using (var writer = XmlWriter.Create(stringWriter, settings))
            {
                xmlserializer.Serialize(writer, t);
                return stringWriter.ToString();
            }
        }

        /// <summary>
        /// 对象序列化为XML字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">Model实体对象</param>
        /// <returns></returns>
        public static string Serialize2<T>(T t)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineChars = "\r\n";
            settings.Encoding = Encoding.UTF8;
            settings.OmitXmlDeclaration = true;
            settings.IndentChars = "    ";

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            //删除顶部的Namespaces：xmlns 和 xsi
            //ns.Add("", "");

            XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
            using (StringWriter stringWriter = new Utf8StringWriter())
            using (var writer = XmlWriter.Create(stringWriter, settings))
            {
                xmlserializer.Serialize(writer, t, ns);
                return stringWriter.ToString();
            }
        }

        /// <summary>
        /// XML反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="xml">xml字符串</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            //using (XmlReader reader = XmlReader.Create(path))
            using (StringReader reader = new StringReader(xml))
            {
                return (T)xmlSerializer.Deserialize(reader);
            }
        }
    }
}